package sellControllers

import (
	"WEB/models"
	"github.com/astaxie/beego/orm"
)

type OrderContoller struct {
	SellBaseController
}

// @router /sell/orderList [get]
func (this *OrderContoller) GetPage() {
	store := this.GetSession("store").(models.Stores)
	var orders []models.Orders
	sql := models.QueryByEqualField(models.Orders{}, "OrderStoreId")
	newOrm := orm.NewOrm()
	_, e := newOrm.Raw(sql, store.StoresId).QueryRows(&orders)
	if e != nil {
		panic(e)
	}
	for i, v := range orders {
		var items []models.OrderItem
		sql = models.QueryByEqualField(models.OrderItem{}, "ItemOrderId")
		_, e := newOrm.Raw(sql, v.OrderId).QueryRows(&items)
		if e != nil {
			panic(e)
		}
		sum := 0.0
		for ii, vv := range items {
			var good models.Goods
			sql = models.QueryByEqualField(models.Goods{}, "GoodId")
			e := newOrm.Raw(sql, vv.ItemGoodsId).QueryRow(&good)
			if e != nil {
				panic(e)
			}
			items[ii].GoodItem = good
			items[ii].ItemSum = float64(items[ii].ItemNums) * (items[ii].ItemPrices)
			sum = sum + items[ii].ItemSum
		}
		orders[i].OrderItems = items
		orders[i].OrderSumPrices = sum
	}
	this.Data["Orders"] = orders
	this.TplName = "sell/orderList.html"
}

// @router /sell/sendOrder [post]
func (this *OrderContoller) ReceiveOrder() {
	orderId := this.GetString("orderId")
	newOrm := orm.NewOrm()
	var temp models.Orders
	sql := models.QueryByPrimaryKey(temp)
	e := newOrm.Raw(sql, orderId).QueryRow(&temp)
	if e != nil {
		this.Data["json"] = map[string]interface{}{
			"code": 1,
		}
		this.ServeJSON()
		return
	}
	store := this.GetSession("store").(models.Stores)
	if temp.OrderStoreId != store.StoresId {
		this.Data["json"] = map[string]interface{}{
			"code": 1,
		}
		this.ServeJSON()
		return
	}

	sql = models.UpdateFieldsByPrimary(temp, "OrderStatus")
	_, e = newOrm.Raw(sql, "已发货", orderId).Exec()
	if e != nil {
		this.Data["json"] = map[string]interface{}{
			"code": 1,
		}
		this.ServeJSON()
		return
	}
	this.Data["json"] = map[string]interface{}{
		"code": 0,
	}
	this.ServeJSON()
}
